package com.zjhb.common.controller;


import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


/**
 * Author :chenqisheng
 * Date   :2016-09-05 15:54.
 */
public class ExcelUtil {
    private final static Logger logger = Logger.getLogger(ExcelUtil.class);


    public static <T> void exportFromBean(ExportBean exportBean, OutputStream out) {
        //读取配置
        String[] headers = exportBean.getHeader();
        List<T> dataset = exportBean.getPoList();
        if (dataset == null || dataset.isEmpty()) {
            //空数据 直接退出
            return;
        }
        // 声明一个工作薄

        XSSFWorkbook workbook = new XSSFWorkbook();
        // 生成一个表格

        XSSFSheet sheet = workbook.createSheet(exportBean.getTitle());
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth(15);
        // 生成一个样式


        XSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式

        //  style.setFillForegroundColor(XSSFColor.toXSSFColor());
        style.setFillForegroundColor(HSSFColor.WHITE.index);
        style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        style.setBorderRight(XSSFCellStyle.BORDER_THIN);
        style.setBorderTop(XSSFCellStyle.BORDER_THIN);
        style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        // 生成一个字体

        XSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.BLACK.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式

        XSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.WHITE.index);
        style2.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        style2.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(XSSFCellStyle.BORDER_THIN);
        style2.setBorderTop(XSSFCellStyle.BORDER_THIN);
        style2.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        style2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        // 生成另一个字体
        XSSFFont font2 = workbook.createFont();
        font2.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);
        // 声明一个画图的顶级管理器


        XSSFDrawing patriarch = sheet.createDrawingPatriarch();

        // 产生表格标题行
        XSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            XSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            XSSFRichTextString text = new XSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        // 遍历集合数据，产生数据行
        Iterator<T> it = dataset.iterator();
        int index = 0;
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            T t = it.next();
            // 利用反射，根据javabean属性的先后顺序，动态调用getXxx()方法得到属性值
            Field[] fields = t.getClass().getDeclaredFields();
            int ignore=0;
            for (int i = 0; i < fields.length; i++) {
                XSSFCell cell = row.createCell(i-ignore);
                cell.setCellStyle(style2);
                Field field = fields[i];
                ExcelIgnore excelIgnore = field.getAnnotation(ExcelIgnore.class);
                if (excelIgnore != null) {
                    ignore++;
                    continue;
                }
                try {
                    field.setAccessible(true);
                    Object value = field.get(t);
                    // 判断值的类型后进行强制类型转换
                    String textValue = null;
                   if (value instanceof Date) {
                        Date date = (Date) value;
                        SimpleDateFormat sdf = new SimpleDateFormat(exportBean.getPattern());
                        textValue = sdf.format(date);
                    } else if (value instanceof Long) {
                        Date date = new Date((Long) value);
                        SimpleDateFormat sdf = new SimpleDateFormat(exportBean.getPattern());
                        textValue = sdf.format(date);
                    } else if (value instanceof byte[]) {
                        // 有图片时，设置行高为60px;
                        row.setHeightInPoints(60);
                        // 设置图片所在列宽度为80px,注意这里单位的一个换算
                        sheet.setColumnWidth(i, (short) (35.7 * 80));
                        // sheet.autoSizeColumn(i);
                        byte[] bsValue = (byte[]) value;
                        XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0,
                                1023, 255, (short) 6, index, (short) 6, index);
                        anchor.setAnchorType(2);
                        patriarch.createPicture(anchor, workbook.addPicture(
                                bsValue, XSSFWorkbook.PICTURE_TYPE_JPEG));
                    } else {
                        // 其它数据类型都当作字符串简单处理
                        if (value == null) {
                            textValue = "";
                        } else {
                            textValue = value.toString();
                        }
                    }
                    // 如果不是图片数据，就利用正则表达式判断textValue是否全部由数字组成
                    if (textValue != null) {
                        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                        Matcher matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            XSSFRichTextString richString = new XSSFRichTextString(
                                    textValue);
                            XSSFFont font3 = workbook.createFont();
//                            font3.setColor(XSSFColor.BLACK.index);
                            richString.applyFont(font3);
                            cell.setCellValue(richString);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }  finally {
                    // 清理资源
                }
            }
        }


        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //导入大量数据，去除反射带来的性能损失和gc，采用map循环和xlsx的文件形式，zj
    public static void exportExcel(String title, String[] headers, List<Map<String, Object>> dataset, OutputStream out,
                                   String pattern, int width) {
        // 声明一个工作薄
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        // 生成一个表格
        Sheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) width);

        // 产生表格标题行
        Row row = sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            Cell cell = row.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 遍历集合数据，产生数据行
        int index = 0;
        for (Map<String, Object> obj : dataset) {
            index++;
            int i = 0;
            row = sheet.createRow(index);
            for (Object value : obj.values()) {
                Cell cell = row.createCell(i);
                i++;
                try { // 判断值的类型后进行强制类型转换
                    String textValue = null;
                    if (value == null) {
                        textValue = "";
                    } else if (value instanceof Date) {
                        Date date = (Date) value;
                        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                        textValue = sdf.format(date);
                    }

                    else {
                        // 其它数据类型都当作字符串简单处理
                        textValue = value.toString();
                    }
                    if (textValue != null) {

                        cell.setCellValue(textValue);
                    }

                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } finally {

                }
            }
        }
        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static Workbook createWorkBook(String fileName, InputStream is) throws IOException {
        if (fileName.toLowerCase().endsWith("xls")) {
            return new HSSFWorkbook(is);
        }
        if (fileName.toLowerCase().endsWith("xlsx")) {
            return new XSSFWorkbook(is);
        }
        return null;
    }

    public static void main(String[] args) throws FileNotFoundException {

    }
}
